//
//  GrowlNotifier.m
//  Shion
//
//  Created by Chris Karr on 12/19/07.
//  Copyright 2007-2008 Audacious Software. All rights reserved.
//

#import "GrowlNotifier.h"
#import "DevicesModel.h"
#import "Device.h"

@implementation GrowlNotifier

- (NSDictionary *) registrationDictionaryForGrowl
{
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	
	NSArray * array = [NSArray arrayWithObject:@"Light Status Changed"];
	
	[dict setObject:array forKey:GROWL_NOTIFICATIONS_ALL];
	[dict setObject:array forKey:GROWL_NOTIFICATIONS_DEFAULT];
	
	return dict;
}
	
- (void) awakeFromNib
{
	cache = [[NSMutableDictionary alloc] init];

	[GrowlApplicationBridge setGrowlDelegate:self];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:DEVICES_UPDATED object:nil];
}

- (void) update: (NSNotification *) msg
{
	for (Device * d in [devices arrangedObjects])
	{
		BOOL update = NO;
		
		if (d.actualStatus.lightLevel == nil)
			update = NO;
		else if ([cache objectForKey:d.address] == nil)
			update = YES;
		else
		{
			if (![[cache objectForKey:d.address] isEqual:d.actualStatus.lightLevel])
				update = YES;
		}
		
		if (update)
		{
			NSInteger actualLevel = [d.actualStatus.lightLevel integerValue];

			NSString * desc = [NSString stringWithFormat:@"%@ is now on.", d.name];
			
			NSData * icon = nil;
			
			if (actualLevel == 0)
			{
				desc = [NSString stringWithFormat:@"%@ is now off.", d.name];
				icon = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"off" ofType:@"png"]];
			}
			else if (actualLevel != 255)
				desc = [NSString stringWithFormat:@"%@ is now at %d.", d.name, ((actualLevel + 1) / 32)];

			[GrowlApplicationBridge notifyWithTitle:d.name description:desc notificationName:@"Light Status Changed"
				iconData:icon priority:0 isSticky:NO clickContext:nil];
				
			[cache setObject:[NSNumber numberWithInteger:actualLevel] forKey:d.address];
		}
	}
}
@end
